﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DateTools = Lucene.Net.Documents.DateTools;
namespace LWrap.IndexSource
{
    public class FileDataSource:IndexDataSource
    {
        FileInfo _rootFileInfo;
        string _folderToIndex;
        int _fileIndex = 0;
        List<FileInfo> _filesToIndex;
        /// <summary>
        /// Assign the folder path, so that to index all the files in the folder
        /// </summary>
        public string FolderToIndex
        {
            get { return _folderToIndex; }
            set
            {
                _folderToIndex = value;
                _rootFileInfo = new FileInfo(_folderToIndex);
            }
        }
        
        public override bool GetNextDoc()
        {
            //recrusively iterate to folder and subfolders and populate the list
            if (_filesToIndex == null)
            {
                this.GetAllFilesToIndex(_rootFileInfo);
            }

            if (_fileIndex >= _filesToIndex.Count)
                return false;

            FileInfo info = _filesToIndex[_fileIndex];
            base.DocName = info.FullName;
            base.ModifiedDate = info.LastWriteTimeUtc.ToShortDateString(); //DateTools.TimeToString(info.LastWriteTime.Ticks, DateTools.Resolution.MINUTE);
            base.DocContent = new System.IO.StreamReader(info.FullName, System.Text.Encoding.Default);

            _fileIndex++;
            return true;
        }

        private void Rewind()
        {
            this.GetAllFilesToIndex(_rootFileInfo);
        }

        /// <summary>
        /// Recrusively iterate through the root folder and collect all the root files and 
        /// files under subfolders.
        /// </summary>
        /// <param name="file"></param>
        private void GetAllFilesToIndex(FileInfo file)
        {
            if (System.IO.Directory.Exists(file.FullName))
            {
                System.String[] files = System.IO.Directory.GetFileSystemEntries(file.FullName);
                if (files != null)
                {
                    for (int i = 0; i < files.Length; i++)
                    {
                        GetAllFilesToIndex(new System.IO.FileInfo(files[i]));
                    }
                }
            }
            else
            {
                if (_filesToIndex == null)
                    _filesToIndex = new List<FileInfo>();

                _filesToIndex.Add(file);
            }
        }
    }
}
